package com.amazon.service.impl;

import com.amazon.model.MenuModel;
import com.amazon.service.MenuService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Override
    public MenuModel makeMenu() {
        MenuModel menuModel = new MenuModel();
        List<String> menuList = new ArrayList<>();
        InputStream inputStream = null;
        Workbook workbook = null;
        try {
            File file = new File("D:\\data\\amazon_data.xlsx");
            inputStream = new FileInputStream(file);
            workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(5);
            Row row = sheet.getRow(1);
            if (row == null) {
                System.out.println("第2行不存在，停止。");
                return menuModel;
            }
            for (int col = 0; col < row.getLastCellNum(); col++) {
                Cell cell = row.getCell(col, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

                if (cell == null || cell.getCellType() == CellType.BLANK) {
                    System.out.println("第2行第" + (col + 1) + "列为空，停止读取。");
                    break; // 停止整个循环
                }
                // 如果不是空，你可以在这里处理这个单元格
                menuList.add(cell.getStringCellValue());
            }
            menuModel.setMenuList(menuList);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(workbook != null){
                try {
                    workbook.close();
                } catch (Exception e){
                    e.printStackTrace();
                }

            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        return menuModel;
    }
}
